package com.xx.job.service.system.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xx.job.entity.system.SysDept;
import com.xx.job.entity.system.SysDept;
import com.xx.job.entity.system.SysMenu;
import com.xx.job.mapper.SysDeptMapper;
import com.xx.job.service.system.SysDeptService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author liangcy
 * @since 2021-01-14
 */
@Service
public class SysDeptServiceImpl extends ServiceImpl<SysDeptMapper, SysDept> implements SysDeptService {

    @Autowired
    private SysDeptMapper sysDeptMapper;

    public List<SysDept> deptTree(){
        return getDeptList(0l);
    }

    private List<SysDept> getDeptList(Long parentId){
        List<SysDept> deptList = new ArrayList<>();
        Map<String,Object> columnMap = new HashMap<>();
        columnMap.put("parent_id",parentId);
        List<SysDept> SysDepts = sysDeptMapper.selectByMap(columnMap);
        if(SysDepts != null && SysDepts.size() != 0){
            for (SysDept sysDept : SysDepts) {
                deptList.add(sysDept);
                List<SysDept> children = getDeptList(sysDept.getDeptId());
                sysDept.setChildren(children);
            }
        }
        return deptList;
    }

    public SysDept selectSysDept(Long id){
        return sysDeptMapper.selectById(id);
    }

    @Override
    public int add(SysDept sysDept) {
        return sysDeptMapper.insert(sysDept);
    }

    @Override
    public int delect(Long id) {
        return sysDeptMapper.deleteById(id);
    }

    @Override
    public int update(SysDept sysDept) {
        return sysDeptMapper.updateById(sysDept);
    }

    @Override
    public List<SysDept> select() {
        return sysDeptMapper.selectByMap(null);
    }

    @Override
    public List<Map<String,Object>> deptTreeselect() {
        return getDeptTreeList(0l);
    }

    private  List<Map<String,Object>> getDeptTreeList(Long parentId){
        List<Map<String,Object>> list = new ArrayList<>();
        QueryWrapper<SysDept> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id",parentId);
        List<SysDept> sysDepts = sysDeptMapper.selectList(wrapper);
        if(sysDepts != null && sysDepts.size() != 0){
            for (SysDept sysDept : sysDepts) {
                Map<String,Object> data = new HashMap<>();
                data.put("id",sysDept.getDeptId());
                data.put("label",sysDept.getDeptName());
                data.put("children",getDeptTreeList(sysDept.getDeptId()));
                list.add(data);
            }
        }
        return list;
    }


}
